package com.joolun.web.controller.scrm;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import com.joolun.common.corp.TenantContext;
import com.joolun.system.domain.ScrmJobUser;
import com.joolun.weixin.service.IScrmJobUserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.joolun.common.annotation.Log;
import com.joolun.common.core.controller.BaseController;
import com.joolun.common.core.domain.AjaxResult;
import com.joolun.common.enums.BusinessType;
import com.joolun.system.domain.ScrmStaff;
import com.joolun.weixin.service.IScrmStaffService;
import com.joolun.common.utils.poi.ExcelUtil;
import com.joolun.common.core.page.TableDataInfo;

/**
 * 企业微信成员Controller
 * 
 * @author joolun
 * @date 2025-02-25
 */
@RestController
@RequestMapping("/scrm/staff")
public class ScrmStaffController extends BaseController
{
    @Autowired
    private IScrmStaffService scrmStaffService;
    @Autowired
    private IScrmJobUserService scrmJobUserService;

    /**
     * 查询企业微信成员列表
     */
    @GetMapping("/list")
    public TableDataInfo list(ScrmStaff scrmStaff)
    {
        startPage();
        List<ScrmStaff> list = scrmStaffService.selectScrmStaffList(scrmStaff);
        return getDataTable(list);
    }

    /**
     * 查询可绑定的企业微信成员列表
     */
    @GetMapping("/listBang")
    public TableDataInfo listBang(ScrmStaff scrmStaff)
    {
        List<ScrmStaff> list = scrmStaffService.selectScrmStaffList(scrmStaff);
        List<ScrmJobUser> jobUserList = scrmJobUserService.list();

        Set<String> existExtIds = jobUserList.stream()
                .map(ScrmJobUser::getExtId)
                .filter(Objects::nonNull) // 过滤 null 值，避免 NPE
                .collect(Collectors.toSet());

        // 2. 过滤 list 中 userId 存在于 existUserIds 的元素（O(n) 时间）
        List<ScrmStaff> resultList = list.stream()
                .filter(staff -> !existExtIds.contains(staff.getExtId())) // 核心过滤逻辑
                .collect(Collectors.toList()); // 生成新列表（不修改原 list）

        return getDataTable(resultList);
    }

    /**
     * 导出企业微信成员列表
     */
    @PreAuthorize("@ss.hasPermi('scrm:staff:export')")
    @Log(title = "企业微信成员", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ScrmStaff scrmStaff)
    {
        List<ScrmStaff> list = scrmStaffService.selectScrmStaffList(scrmStaff);
        ExcelUtil<ScrmStaff> util = new ExcelUtil<ScrmStaff>(ScrmStaff.class);
        util.exportExcel(response, list, "企业微信成员数据");
    }

    /**
     * 获取企业微信成员详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(scrmStaffService.selectScrmStaffById(id));
    }

    /**
     * 新增企业微信成员
     */
    @PreAuthorize("@ss.hasPermi('scrm:staff:add')")
    @Log(title = "企业微信成员", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ScrmStaff scrmStaff)
    {
        scrmStaff.setCreateBy(getUsername());
        return toAjax(scrmStaffService.insertScrmStaff(scrmStaff));
    }

    /**
     * 修改企业微信成员
     */
    @PreAuthorize("@ss.hasPermi('scrm:staff:edit')")
    @Log(title = "企业微信成员", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ScrmStaff scrmStaff)
    {
        scrmStaff.setCreateBy(getUsername());
        return toAjax(scrmStaffService.updateScrmStaff(scrmStaff));
    }

    /**
     * 删除企业微信成员
     */
    @PreAuthorize("@ss.hasPermi('scrm:staff:remove')")
    @Log(title = "企业微信成员", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(scrmStaffService.deleteScrmStaffByIds(ids));
    }


    @GetMapping("/sync")
    @ApiOperation(value = "同步企业微信员工数据")
    @Log(title = "同步企业微信数据", businessType = BusinessType.DELETE)
//    @ApiImplicitParam(value = "外部企业ID", name = "extCorpId", required = true)
    public AjaxResult syncStaff() {
        Assert.isTrue(StringUtils.isNotBlank(TenantContext.getTenantId()), "外部企业ID不能为空");
        return AjaxResult.success(scrmStaffService.sync(TenantContext.getTenantId()));
    }

}
